package com.controller;

import java.io.IOException;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;









import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.PongMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.BinaryWebSocketHandler;

import com.fasterxml.jackson.databind.ObjectMapper;



/**
 * 
 * 包      名 ：  com.controller
 * 文 件 名 : MyWebSocketHandler
 * 描       述: 处理二进制数据
 * 作        者： 超哥
 * 创建时间： 2016年8月14日 上午10:20:46
 * 版         本：1.0
 */
public class WebRTCWebSocketHandler extends BinaryWebSocketHandler {
    
	/**
	 * 连接池
	 */
	public static final Map<String, List<WebSocketSession>> allConnections = new Hashtable<String, List<WebSocketSession>>();
	
	/**
	 * 两个人的房间的Id
	 */
	private String roomId;

	public String getConferenceId() {
		return roomId;
	}

	public void setConferenceId(String roomId) {
		this.roomId = roomId;
	}
	/**
	 * 连接建立成功后回调
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session)
			throws Exception {
		// TODO Auto-generated method stub
		//获取连接参数 
		this.roomId = (String) session.getAttributes().get("roomId");
    	System.out.println("WebRTCWebSocketHandler roomId=="+roomId);  
    	List<WebSocketSession> oneConnection = allConnections.get(roomId);
    	if (null == oneConnection) {
			List<WebSocketSession> newConnection = new ArrayList<WebSocketSession>();
			newConnection.add(session);
			allConnections.put(roomId, newConnection);
		} else {
			oneConnection.add(session);
		}
    	
    	ObjectMapper objectMapper = new ObjectMapper();  
    	String message= objectMapper.writeValueAsString("{'message':'websocket open!\'}");
        
    	//连接成功将数据返回客户端
    	broadcast(message);
    	
    	super.afterConnectionEstablished(session);
	}
	/**
     * 客户端发送服务器的消息时，的处理函数，在这里收到消息之后可以分发消息
     */
	@Override
	public void handleMessage(WebSocketSession session,
			WebSocketMessage<?> message) throws Exception {
		try {  
            if (message instanceof PongMessage) {//WebSocket连接会有心跳消息，所以需要过滤  
                return;  
            }else if(message instanceof BinaryMessage){ //二进制消息
            	System.out.println("收到二进制发送的数据"+message.getPayload());
            
              
            	
            } else {  
            	System.out.println("收到文本数据的数据"+message.getPayload());
            	// 这里处理的是文本数据
        		broadcast((String) message.getPayload());
            }  
        	
        } catch (Exception e) {  
            return;  
        }  
	
	}
    
	/**
     * 二进制消息
     */
	@Override
	protected void handleBinaryMessage(WebSocketSession session,BinaryMessage message) throws Exception {
		// TODO Auto-generated method stub
		super.handleBinaryMessage(session, message);
	}

	
	/**
     * 消息传输过程中出现的异常处理函数
     */
	@Override
	public void handleTransportError(WebSocketSession session,
			Throwable exception) throws Exception {
		// TODO Auto-generated method stub
		super.handleTransportError(session, exception);
	}
  
	/**
	 * 连接关闭的时候的回调
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session,
			CloseStatus status) throws Exception {
		

		List<WebSocketSession> oneConnection = allConnections.get(roomId);

		if (null != oneConnection) {
			System.out.println("关闭视频会话移除连接"+session.getId());
			
			oneConnection.remove(session);
			System.out.println("oneConnection移除后的大小=="+oneConnection.size());
			if (null != oneConnection && oneConnection.size() < 1) {
				allConnections.remove(roomId);
				
			}
		}

		String message = "{\"message\":\"webSocket close!\"}";
		broadcast(message);
		
		super.afterConnectionClosed(session, status);
	}
	
	@Override
	public boolean supportsPartialMessages() {
		// TODO Auto-generated method stub
		return super.supportsPartialMessages();
	}
	
	
	// 将数据传回客户端
    private void broadcast(String message) {
			System.out.println(message.toString());
			List<WebSocketSession> oneConnection = allConnections.get(roomId);
			if (null != oneConnection) {
				for (WebSocketSession connection : oneConnection) {
					try {
						
						WebSocketMessage retunstr = new TextMessage(message.getBytes());
						if (connection.isOpen()) {
							System.out.println("message===="+message);
							connection.sendMessage(retunstr);
						}
						
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
   
	  
}
